package com.ruoyi.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class ApiAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisCache redisCache;

    private static final String TOKEN_PREFIX = "Bearer ";
    private static final String REDIS_API_KEY_PREFIX = "api:auth:";
    private static final long TOKEN_EXPIRE_DAYS = 30;

    // 白名单路径
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/api/v1/phoneCheck",           // 发送验证码
            "/api/v1/login/phone",          // 手机号登录
            "/api/v1/user/info/",           // 获取用户信息
            "/api/v1/type",             // 短信验证码
            "/api/v1/problems",             // 短信验证码
            "/api/v1/user/add",             // 短信验证码
            "/api/v1/common/upload"          // 文件上传
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestPath = request.getRequestURI();

        // 检查是否是白名单路径
        for (String whitePath : WHITE_LIST) {
            if (requestPath.startsWith(whitePath)) {
                return true;
            }
        }

        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authHeader) || !authHeader.startsWith(TOKEN_PREFIX)) {
            handleUnauthorized(response, "未登录");
            return false;
        }

        // 提取token
        String token = authHeader.substring(TOKEN_PREFIX.length());
        String redisKey = REDIS_API_KEY_PREFIX + token;

        // 从Redis获取用户信息
        Object userInfo = redisCache.getCacheObject(redisKey);
        if (userInfo == null) {
            handleUnauthorized(response, "登录已过期");
            return false;
        }

        // 刷新token有效期
        redisCache.expire(redisKey, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);

        // 将用户信息放入request属性中，供后续使用
        request.setAttribute("userInfo", userInfo);
        return true;
    }

    private void handleUnauthorized(HttpServletResponse response, String message) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(JSON.toJSONString(AjaxResult.error(401, message)));
    }
} 